#include "protocol.h"

int main(int argc, char *argv[]) {
    int sockfd;
    FILE *local;
    size_t amt;
    void *storage = malloc(MAX_FILE_DATA);
    transfer_header head;

    if (argc != 4) {
        fprintf(stderr, "Usage: ftpc dest-host dest-port local-file\n");
        exit(EXIT_FAILURE);
    }

    /* open the file for reading and determine the size */
    local = fopen(argv[3], "rb");
    if (local == NULL) {
        perror(NULL);
        exit(EXIT_FAILURE);
    }
    fseek(local, 0L, SEEK_END);
    head.size = ftell(local);
    fseek(local, 0L, SEEK_SET);

    sockfd = SOCKET(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    if (BIND(sockfd, argv[1], atoi(argv[2])) < 0) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    /* send the protocol header and data */
    memset(&head.name, 0, sizeof head.name);
    if (strrchr(argv[3], '/') == NULL)
        strncpy(head.name, argv[3], MAX_FILENAME);
    else
        strncpy(head.name, strrchr(argv[3], '/')+1, MAX_FILENAME);
#ifdef DEBUG
    printf("Now sending file %s of size %u\n", head.name, head.size);
#endif
    head.size = htonl(head.size);
    SEND(sockfd, &head, sizeof head);
    do {
        amt = fread(storage, 1, MAX_FILE_DATA, local);
        if (amt > 0) {
            assert(amt == SEND(sockfd, storage, amt));
#ifdef DEBUG
            printf("Reading %u bytes\n", amt);
#endif
        }
    } while (amt > 0);

    if (fclose(local)) {
        perror(NULL);
        exit(EXIT_FAILURE);
    }
    free(storage);
    CLOSE(sockfd);
    return EXIT_SUCCESS;
}
